<?php
/**
 * Cashiers Classes Controller
 *
 * PHP 5.2+
 *
 * Copyright 2012
 * @date 21-April-2012
 * @author 
 * @property Auth $Auth
 * @version 0.0.1
 **/
/**
* @property CashierType $CashierType
* @property Cashier $Cashier
* @property Interest $Interest
* @property CashierInterest $CashierInterest
* @property SendMailComponent $SendMail
* @property EmstrainingComponent $Emstraining
* @property Mobilecode $Mobilecode test
* @property CashierOvertime $CashierOvertime */

class CashiersController extends AppController 
{

    public $sN = 'Cashier'; 
    public $pN = 'cashier';
    public $lN = 'cashiers';    
    public $conditions = array();
    public $components = array(
                        'RequestHandler',
                        'CakePdf.CakePdf' => array(
                            'prefix' => 'mypdf',
                            'orientation' => 'L'
                        ),"Emstraining","SendMail","Export"
                      );
    public $paginate = array(
        'CashierSell'=>array(
            'order'=>array('created'=>'desc'),
            'limit'=>25
        ),
        'Gift' => array(
            'order' => array('id' => 'desc'),
            'limit' => 15
        )
    );
    public function beforeFilter() {
        parent::beforeFilter();
        $this->loadModel("Cashier");
        //pr($this->Auth->user());die;
        if($this->Auth->user("indentify")=="cashier"){
            $this->layout = "cashier";
        }
        $this->set('sN', $this->sN);        
        $this->set('pN', $this->pN);
        $this->set('lN', $this->lN);        
        if(!$this->request->is("ajax")){
            if(!$this->Auth->user('id')&&$this->request->params['action']!="login"){
                $this->Session->setFlash("You must to login first!");
                $this->redirect("/");
            }
        }
        if ($this->Auth->user("indentify")=="customer") {
            $this->Session->setFlash("You don't have permission to access this page!");
            $this->redirect("/");
        }
    }
    public function admin_index() {
        //$this->loadModel("CashierShopperGroup");
        $pagi = array();
        $this->paginate = array(
            'limit' => 20,
            'conditions'=>$pagi
        );
        $values = $this->paginate($this->sN);
        $this->set('values', $values);
    }
    public function admin_add() {
        if(!empty($this->data)){
            $check = 1;
            if($check==1){
                $this->request->data['Cashier']['created_by']= $this->Auth->user("id");
                $this->request->data['Cashier']['status'] = 1;
                if(!empty($this->data['Cashier']['working_days'])){
                    $this->request->data['Cashier']['working_days'] = implode(",", $this->data['Cashier']['working_days']);
                }
                if($this->Cashier->save($this->data)) {
                    $cusID = $this->Cashier->id;
                    $this->redirect(array('action'=>'index'));
                }
            }
        }
        $this->set("interests",  array('Monday'=>"Monday","TuesDay"=>"TuesDay","Wednesday"=>"Wednesday","Thursday"=>"Thursday","Friday"=>"Friday","Saturday"=>"Saturday","Sunday"=>"Sunday"));
    }
    public function admin_edit($casher_id) {
        $casher = $this->Cashier->read(null,$casher_id);
        if(!empty($this->data)){
            $check = 1;
            if($check==1){
                if(!empty($this->data['Cashier']['working_days'])){
                    $this->request->data['Cashier']['working_days'] = implode(",", $this->data['Cashier']['working_days']);
                }
                if($this->Cashier->save($this->data)) {
                    $cusID = $this->Cashier->id;
                    $this->redirect(array('action'=>'index'));
                }
            }
        }else{
            $this->request->data = $casher;
        }
        
        $this->set("interested",  explode(",", $casher['Cashier']['working_days']));
        $this->set("interests",  array('Monday'=>"Monday","TuesDay"=>"TuesDay","Wednesday"=>"Wednesday","Thursday"=>"Thursday","Friday"=>"Friday","Saturday"=>"Saturday","Sunday"=>"Sunday"));
    }
    public function admin_delete(){
        
    }
    public function admin_reports($cashier_id=null){
        $this->loadModel("CashierSell");
        $conditions = array('CashierSell.cashier_id'=>  $cashier_id);
        if(!empty($this->data)){
            if(!empty($this->data['CashierSell']['code'])){
                $conditions['CashierSell.code']=$this->data['CashierSell']['code'];
            }
            if(!empty($this->data['CashierSell']['from_created'])){
                $conditions["DATE_FORMAT(CashierSell.created,'%Y-%m-%d') >= "]=$this->data['CashierSell']['from_created'];
            }
            if(!empty($this->data['CashierSell']['created'])){
                $conditions["DATE_FORMAT(CashierSell.created,'%Y-%m-%d') <= "]=$this->data['CashierSell']['created'];
            }
        }
        $this->CashierSell->unbindModel(array('belongsTo'=>array('Cashier','Voucher','Gift')));
        $overtimes = $this->paginate("CashierSell",$conditions);
        $this->set('cashier',$this->Cashier->read(null,$cashier_id));
        $this->set('cashier_id',$cashier_id);
        $this->set("values",$overtimes);
    }
    public function report() {
        $this->loadModel("CashierSell");
        $conditions = array('CashierSell.cashier_id'=>  $this->Auth->user('id'));
        if(!empty($this->data)){
            if(!empty($this->data['CashierSell']['code'])){
                $conditions['CashierSell.code']=$this->data['CashierSell']['code'];
            }
            if(!empty($this->data['CashierSell']['from_created'])){
                $conditions["DATE_FORMAT(CashierSell.created,'%Y-%m-%d') >= "]=$this->data['CashierSell']['from_created'];
            }
            if(!empty($this->data['CashierSell']['created'])){
                $conditions["DATE_FORMAT(CashierSell.created,'%Y-%m-%d') <= "]=$this->data['CashierSell']['created'];
            }
        }
        $this->CashierSell->unbindModel(array('belongsTo'=>array('Cashier','Voucher','Gift')));
        $overtimes = $this->paginate("CashierSell",$conditions);
        $this->set("values",$overtimes);
    }
    public function login() {
        $this->layout = "adminlogin";
        $this->setCashierLogin();
        if($this->request->is("post")){
            $customer = $this->Cashier->find('first',array('conditions'=>array('cashier_id'=>  $this->data['Cashier']['username'],'password'=>  AuthComponent::password( $this->data['Cashier']['password']))));
            if(!empty($customer)){
                if($customer['Cashier']['status']==Cashier::ACTIVE){
                    if ($this->Auth->login($customer['Cashier'])) {
                        $this->Session->write("Auth.User.indentify","cashier");
                        $this->redirect(array('controller' => 'cashiers', 'action' => 'index','admin'=>false));
                    } else {
                        $this->Session->setFlash(__('Invalid id or password, try again'));
                    }
                }else {
                    $this->Session->setFlash(__('Your account has been blocked ! Please contact with administrator'));
                }
            }else {
                $this->Session->setFlash(__('Invalid id or password, try again'));
            }
        }
    }
    public function index() {
        $this->set("cashier",  $this->Cashier->read(null,  $this->Auth->user("id")));
    }
    public function add_overtime() {
        $this->loadModel("CashierOvertime");
        if(!empty($this->data)){
            $this->request->data['CashierOvertime']['cashier_id']=  $this->Auth->user("id");
            $this->request->data['CashierOvertime']['is_confirm']=  0;
            $this->CashierOvertime->create();
            $this->CashierOvertime->save($this->data);
            $this->Session->setFlash("The change has been saved.But you need admin confirm you changes");
            $this->redirect(array('action'=>'index'));
        }
    }
    public function overtimes(){
        $this->loadModel("CashierOvertime");
        $overtimes = $this->paginate("CashierOvertime",array('CashierOvertime.cashier_id'=>  $this->Auth->user('id')));
        $this->set("values",$overtimes);
    }
    public function admin_overtimes($cashier_id=null){
        $this->loadModel("CashierOvertime");
        $overtimes = $this->paginate("CashierOvertime",array('CashierOvertime.cashier_id'=>  $cashier_id));
        $this->set("values",$overtimes);
    }
    public function delete_overtime($overtime_id=null){
        $this->loadModel("CashierOvertime");
        if(!$overtime_id){
            $this->Session->setFlash("Invalid over time");
            $this->redirect(array('controller'=>'cashiers','action'=>'overtimes'));
        }
        $this->CashierOvertime->id = $overtime_id;
        $this->CashierOvertime->delete();
        $this->Session->setFlash("Deleted");
        $this->redirect(array('controller'=>'cashiers','action'=>'overtimes'));
    }
    public function check_code($code=null){
        $return = array();
        $this->autoLayout=false;    
        $this->loadModel("Voucher");
        $this->loadModel("Gift");
        if($code){
            $voucher = $this->Voucher->findByCode($code);
            if(!empty($voucher)){
                $arr = array();
                $arr['type']="voucher";
                $arr['info']=$voucher['Voucher'];
                $arr['expired']=$voucher['Voucher']['expired_date'];
                $return[]=$arr;
            }

            $voucher = $this->Gift->findByCode($code);
            if(!empty($voucher)){
                $arr = array();
                $arr['type']="gift";
                $arr['info']=$voucher['Gift'];
                $arr['expired']=$voucher['Gift']['expiry'];
                $return[]=$arr;
            }
        }
        $this->set("cards",$return);
    }
    public function admin_approve_overtime($overtime_id=null){
        $this->loadModel("CashierOvertime");
        if(!$overtime_id){
            $this->Session->setFlash("Invalid over time");
            $this->redirect(array('controller'=>'cashiers','action'=>'index'));
        }
        $this->CashierOvertime->id = $overtime_id;
        $this->CashierOvertime->saveField("status", CashierOvertime::CONFIRMED);
        $this->CashierOvertime->saveField("approved_by", $this->Auth->user("id"));
        $this->Session->setFlash("Confirmed");
        $this->redirect(array('controller'=>'cashiers','action'=>'index'));
    }
    public function admin_cancel_overtime($overtime_id=null){
        $this->loadModel("CashierOvertime");
        if(!$overtime_id){
            $this->Session->setFlash("Invalid over time");
            $this->redirect(array('controller'=>'cashiers','action'=>'index'));
        }
        $this->CashierOvertime->id = $overtime_id;
        $this->CashierOvertime->saveField("status", CashierOvertime::CANCELLED);
        $this->CashierOvertime->saveField("approved_by", $this->Auth->user("id"));
        $this->Session->setFlash("Cancelled");
        $this->redirect(array('controller'=>'cashiers','action'=>'index'));
    }
    public function sell() {
        $this->loadModel("CashierSell");
        $this->loadModel('Voucher');
        $this->loadModel('Gift');
        
        if(!empty($this->data)){
            
            $type = $this->data['CashierSell']['type'];
            if($type=="voucher"){
                $voucher = $this->Voucher->read(null,$this->data['CashierSell']['voucher_id']);
                if($this->request->data['CashierSell']['amount']>$voucher['Voucher']['value']){
                    $amount_out = $this->request->data['CashierSell']['amount']-$voucher['Voucher']['value'];
                    $this->Voucher->id = $voucher['Voucher']['id'];
                    $this->Voucher->saveField('value',0);
                    $this->Session->setFlash("The voucher has been used. The customer should pay more $amount_out$");
                }elseif($this->request->data['CashierSell']['amount']==$voucher['Voucher']['value']){
                    $this->Voucher->id = $voucher['Voucher']['id'];
                    $this->Voucher->saveField('value',0);
                    $this->Session->setFlash("The voucher has been used.");
                }else{
                    $amount_out = $voucher['Voucher']['value']-$this->request->data['CashierSell']['amount'];
                    $this->Voucher->id = $voucher['Voucher']['id'];
                    $this->Voucher->saveField('value',$amount_out);
                    $this->Session->setFlash("The voucher has been used. THe value of voucher now is $amount_out$");
                }
            }elseif($type=="gift"){
                $gift = $this->Gift->read(null,$this->data['CashierSell']['gift_id']);
                if($this->request->data['CashierSell']['amount']>$gift['Gift']['value']){
                    $amount_out = $this->request->data['CashierSell']['amount']-$gift['Gift']['value'];
                    $this->Gift->id = $gift['Gift']['id'];
                    $this->Gift->saveField('value',0);
                    $this->Session->setFlash("The gift has been used. The customer should pay more $amount_out$");
                }elseif($this->request->data['CashierSell']['amount']==$gift['Gift']['value']){
                    $this->Gift->id = $gift['Gift']['id'];
                    $this->Gift->saveField('value',0);
                    $this->Session->setFlash("The gift has been used.");
                }else{
                    $amount_out = $gift['Gift']['value']-$this->request->data['CashierSell']['amount'];
                    $this->Gift->id = $gift['Gift']['id'];
                    $this->Gift->saveField('value',$amount_out);
                    $this->Session->setFlash("The gift has been used. THe value of gift now is $amount_out$");
                }
            }
            $this->request->data['CashierSell']['created']=date("Y-m-d H:i:s");
            $this->request->data['CashierSell']['cashier_id']=$this->Auth->user('id');
            $this->CashierSell->create();
            $this->CashierSell->save($this->data);
        }
    }
    public function logout() {
        $this->autoRender = false;
        $this->Session->destroy();
        $this->Session->setFlash(__('Successfully logged out!', true));                		
        $this->redirect("/");
    }
    
    
    public function admin_inactive($customer_id=null) {
        if(!$customer_id){
            $this->Session->setFlash("Invalid Cashier Id");
            $this->redirect(array('controller'=>'cashiers','action'=>'index'));
        }
        $this->Cashier->id = $customer_id;
        $this->Cashier->saveField("status", Cashier::INACTIVE);
        $this->Session->setFlash("The casher has been disabled");
        $this->redirect(array('controller'=>'cashiers','action'=>'index'));
    }
    public function admin_active($customer_id=null) {
        if(!$customer_id){
            $this->Session->setFlash("Invalid Cashier Id");
            $this->redirect(array('controller'=>'cashiers','action'=>'index'));
        }
        $this->Cashier->id = $customer_id;
        $this->Cashier->saveField("status", Cashier::ACTIVE);
        $this->Session->setFlash("The casher has been actived");
        $this->redirect(array('controller'=>'cashiers','action'=>'index'));
    }
    public function changepass($id=null){
        if(empty($this->data)) {
            $this->request->data = $this->Cashier->read(null, $this->Auth->user('id'));
        } else {
            $this->Cashier->id = $this->Auth->user('id');
            if($this->Cashier->save($this->data)) {
                $this->Session->setFlash(__('Updated Successfully', true));
                $this->redirect(array('controller' => 'cashiers', 'action' => 'index', 'admin' => false));
            }
        }
    }
    public function create_giftcard() {
        $this->loadModel('Gift');
        if ($this->request->is('post')) {    
            //pr($this->data);die;
            $this->request->data['Gift']['cashier_id']=  $this->Auth->user('id');
            if ($this->Gift->save($this->request->data)) {
                $this->redirect(array('action' => 'view_gift',$this->Gift->id));
            } else {
                $this->Session->setFlash('Could not save Gift Card, try later.');
            }
        }
    }
    public function giftcard(){
        $this->loadModel('Gift');
        $this->set('gifts', $this->paginate('Gift',array('cashier_id'=>  $this->Auth->user('id'))));
    }
    public function view_gift($id=null){
        $this->loadModel("Gift");
        if (!$id) {
                $this->Session->setFlash(__('Invalid Gift Card', true));
                $this->redirect(array('action' => 'index'));
        }
        $gift = $this->Gift->read(null, $id);
        $this->Zend->writeGiftCode(WWW_ROOT.'/files/vouchers/'.$gift['Gift']['code'].'.png',$gift['Gift']['code']);
        $this->set('gift', $gift );
    }
    public function generate_code() {
         $this->autoRender=false;
         return $this->Emstraining->loyalty_gift_number();
     }
    public function mypdf_print_gift($id = null) {
        $this->loadModel('Gift');
        $this->CakePdf->addStyle('pdf_style.css');
        $gift = $this->Gift->read(null, $id);
        $this->CakePdf->setFilename('GiftCard_'.$gift['Gift']['code']);
        $this->Zend->writeGiftCode(WWW_ROOT.'/files/vouchers/'.$gift['Gift']['code'].'.png',$gift['Gift']['code']);
        $this->set('gift', $gift);
    }
    public function mypdf_print_report($from=null,$to=null,$code=null) {
        $this->loadModel("CashierSell");
        $conditions = array('CashierSell.cashier_id'=>  $this->Auth->user('id'));
        $title = "Selling report";
        if($code!=0){
            $conditions['CashierSell.code']=$code;
            $title.=" for $code";
        }
        if($from!=0){
            $conditions["DATE_FORMAT(CashierSell.created,'%Y-%m-%d') >= "]=$from;
            $title.=" From $from";
        }
        if($to!=0){
            $conditions["DATE_FORMAT(CashierSell.created,'%Y-%m-%d') <= "]=$to;
            $title.=" To $to";
        }
        $this->CashierSell->unbindModel(array('belongsTo'=>array('Cashier','Voucher','Gift')));
        $overtimes = $this->paginate("CashierSell",$conditions);
        //$this->CakePdf->addStyle('selling_pdf_style.css');
        $this->CakePdf->setFilename($title);
        $this->set('title',$title);
        $this->set('values',$overtimes);
    }
    
    public function mypdf_print_report2($cashier_id=null) {
        $this->loadModel("CashierSell");
        $conditions = array('CashierSell.cashier_id'=>  $cashier_id);
        $cashier = $this->Cashier->read(null,$cashier_id);
        $title = "Selling report of {$cashier['Cashier']['name']}";
        $this->CashierSell->unbindModel(array('belongsTo'=>array('Cashier','Voucher','Gift')));
        $overtimes = $this->paginate("CashierSell",$conditions);
        //$this->CakePdf->addStyle('selling_pdf_style.css');
        $this->CakePdf->setFilename($title);
        $this->set('title',$title);
        $this->set('values',$overtimes);
        $this->render("mypdf_print_report");
    }
    
    public function admin_export_xls($cashier_id=null){
        $this->autoRender=false;
        $this->loadModel("CashierSell");
        $conditions = array('CashierSell.cashier_id'=>  $cashier_id);
        $cashier = $this->Cashier->read(null,$cashier_id);
        $title = "Selling report of {$cashier['Cashier']['name']}";
        $this->CashierSell->unbindModel(array('belongsTo'=>array('Cashier','Voucher','Gift')));
        $overtimes = $this->paginate("CashierSell",$conditions);
        //$this->CakePdf->addStyle('selling_pdf_style.css');
        $this->Export->export_selling_list($title,$overtimes);
    }
    public function export_xls($from=null,$to=null,$code=null){
        $this->autoRender=false;
        $this->loadModel("CashierSell");
        $conditions = array('CashierSell.cashier_id'=>  $this->Auth->user('id'));
        $title = "Selling report";
        if($code!=0){
            $conditions['CashierSell.code']=$code;
            $title.=" for gift-voucher : $code";
        }
        if($from!=0){
            $conditions["DATE_FORMAT(CashierSell.created,'%Y-%m-%d') >= "]=$from;
            $title.=" From $from";
        }
        if($to!=0){
            $conditions["DATE_FORMAT(CashierSell.created,'%Y-%m-%d') <= "]=$to;
            $title.=" To $to";
        }
        $this->CashierSell->unbindModel(array('belongsTo'=>array('Cashier','Voucher','Gift')));
        $overtimes = $this->paginate("CashierSell",$conditions);
        //$this->CakePdf->addStyle('selling_pdf_style.css');
        $this->Export->export_selling_list($title,$overtimes);
    }
}